﻿
using YiShop.System.Entities;

namespace YiShop.System.Repositories
{
    public class SysDictDataRepository : BaseRepository<SysDictData, SysDictDataDto>
    {
        public SysDictDataRepository(ISqlSugarRepository<SysDictData> sqlSugarRepository) : base(sqlSugarRepository)
        {
        }

        public override ISugarQueryable<SysDictDataDto> DtoQueryable(SysDictDataDto dto)
        {
            return Repo.AsQueryable()
                .WhereIF(dto.DictCode > 0, (t) => t.DictCode == dto.DictCode)
                .WhereIF(!string.IsNullOrEmpty(dto.DictType), (t) => t.DictType == dto.DictType)
                .WhereIF(!string.IsNullOrEmpty(dto.DictLabel), (t) => t.DictLabel!.Contains(dto.DictLabel!))
                .WhereIF(!string.IsNullOrEmpty(dto.Status), (t) => t.Status == dto.Status)
                .Select<SysDictDataDto>();
        }

        public override ISugarQueryable<SysDictData> Queryable(SysDictDataDto dto)
        {
            return Repo.AsQueryable()
                .WhereIF(dto.DictCode > 0, (t) => t.DictCode == dto.DictCode)
                .WhereIF(!string.IsNullOrEmpty(dto.DictType), (t) => t.DictType == dto.DictType)
                .WhereIF(!string.IsNullOrEmpty(dto.DictLabel), (t) => t.DictLabel!.Contains(dto.DictLabel!))
                .WhereIF(!string.IsNullOrEmpty(dto.Status), (t) => t.Status == dto.Status);
        }

        /// <summary>
        /// 查询字典类型下数据
        /// </summary>
        /// <param name="dictType"></param>
        /// <returns></returns>
        public async Task<List<SysDictData>> SelectDictDataByTypeAsync(string dictType)
        {
            if (string.IsNullOrEmpty(dictType))
                return null!;

            var query = new SysDictDataDto { DictType = dictType };
            return await GetListAsync(query);
        }

        /// <summary>
        /// 同步修改字典类型
        /// </summary>
        /// <param name="oldDictType">旧字典类型</param>
        /// <param name="newDictType">新旧字典类型</param>
        /// <returns></returns>
        public async Task<int> UpdateDictDataTypeAsync(string oldDictType, string newDictType)
        {
            return await Updateable()
                  .SetColumns(col => col.DictType == newDictType)
                  .Where(col => col.DictType == oldDictType)
                  .ExecuteCommandAsync();
        }

        /// <summary>
        /// 查询字典数据
        /// </summary>
        /// <param name="dictType">字典类型</param>
        /// <returns></returns>
        public async Task<int> CountDictDataByTypeAsync(string dictType)
        {
            return await base.CountAsync(c => c.DictType == dictType);
        }

    }
}